import java.util.LinkedList;
import java.util.Queue;

/**
 * 104. 二叉树的最大深度
 */
public class Solution_104 {
    /**
     * 方法二：递归深度优先搜索
     * <p>
     * 时间复杂度：O(N)，N 为节点数
     * <p>
     * 空间复杂度：O(H)，H 为二叉树高度
     */
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }

    /**
     * 方法一：广度优先搜索
     * <p>
     * 时间复杂度：O(N)，N 为节点数
     * <p>
     * 空间复杂度：O(N)，N 为节点数
     */
    public int maxDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            depth++;
        }
        return depth;
    }

    public static void main(String[] args) {
        Solution_104 solution = new Solution_104();
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(9);
        TreeNode right = new TreeNode(20, new TreeNode(15), new TreeNode(7));
        root.left = left;
        root.right = right;
        int ans = solution.maxDepth(root);
        System.out.println(ans);
    }
}
